package cn.getech.data.metadata.model.excel;

import cn.getech.data.metadata.annotation.ExplicitConstraint;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 表头添加备注
 * @author: wangzhaowen：kiss
 * @create: 2020/10/17 13:04
 * @version: 2020/10/17
 **/
@Slf4j
public class MyCellWriteHandler extends AbstractCellWriteHandler {

    private Map<Integer, String> msgMap = new HashMap<>();
    public MyCellWriteHandler(Class dataClass) {
        //循环获取对应列得下拉列表信息
        Field[] declaredFields = dataClass.getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field field = declaredFields[i];
            //解析注解信息
            ExplicitConstraint desc = field.getAnnotation(ExplicitConstraint.class);
            if (desc != null) {
                String message = desc.desc();
                if (StringUtils.isNotEmpty(message)) {
                    msgMap.put(i, message);
                }
            }
        }
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead){
            int columnIndex = cell.getColumnIndex();
            String msg = msgMap.get(columnIndex);
            if (StringUtils.isNotEmpty(msg)) {
                Drawing<?> drawing = cell.getSheet().createDrawingPatriarch();
                Comment cellComment = drawing.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, columnIndex, 0, columnIndex + 2, 5));
                cellComment.setString(new XSSFRichTextString(msg));
                cell.setCellComment(cellComment);
            }

        }
    }

}
